package com.cms.manage.interceptor;

import java.io.PrintWriter;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cms.manage.common.ConmonConfig;
import com.cms.manage.model.CmsUser;
import com.cms.manage.util.Constant;
import com.cms.manage.util.JWTUtil;

import io.jsonwebtoken.Claims;
public class AuthInterceptor implements HandlerInterceptor{
	/** 
     * 在业务处理器处理请求之前被调用 
     * 如果返回false 
     *     从当前的拦截器往回执行所有拦截器的afterCompletion(),再退出拦截器链
     * 如果返回true 
     *    执行下一个拦截器,直到所有的拦截器都执行完毕 
     *    再执行被拦截的Controller 
     *    然后进入拦截器链, 
     *    从最后一个拦截器往回执行所有的postHandle() 
     *    接着再从最后一个拦截器往回执行所有的afterCompletion() 
     *    springboot
     *    只有经过DispatcherServlet 的请求，才会走拦截器链，我们自定义的Servlet 请求是不会被拦截的
     */  
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String servletPath = request.getServletPath();
		//不拦截登陆接口
		if(servletPath.startsWith("/cms/user/") || servletPath.startsWith("/v2/api-docs")||servletPath.startsWith("/swagger-resources")||servletPath.startsWith("/error")){
			return true;
		}else{//拦截接口
			//判断session是否失效或被篡改
			String cmsUser =(String)request.getSession().getAttribute(Constant.SESSION_USER);
			Integer userId =(Integer)request.getSession().getAttribute(Constant.SESSION_USER_ID);
			String userJson ="";
			CmsUser user;
			try {
				Claims  claims = JWTUtil.parseJWT(cmsUser);
				 //解密获得 userjson
			     userJson = claims.getSubject();
			   //校验用户id是否一致
			    user = JSON.parseObject(userJson, CmsUser.class);
			   if(!(userId.intValue()==user.getId().intValue())){//数据被篡改,清空session。			
				   clearSession(request);
				   return NO_LOGIN(response);				 
			   }
			} catch (Exception e) {
				//报异常 session失效,清空session。			
				clearSession(request);
				return NO_LOGIN(response);	
			}
			  //正常重置session有限期
			  Map<String, String> map = new HashMap<String, String>();
			  map.put("subject", userJson);
		      map.put("minutes", "360");//设置失效时间为6个小时
		       try {
		        	 cmsUser = JWTUtil.createJWT(map);
		        	 request.getSession().setAttribute(Constant.SESSION_USER, cmsUser);
		        	 request.getSession().setAttribute(Constant.SESSION_USER_ID, user.getId());
		        	 request.getSession().setAttribute(Constant.SESSION_NIKE_NAME, user.getNikename());		        	
				} catch (ParseException e) {
					return NO_LOGIN(response);
				}
			return true;
		}
		//拦截处理
		/*if (servletPath.startsWith("/user/showUser")) {
	        	//重定向
	        	response.sendRedirect("/orderError/error.do");
				//log.warn("wmall sign validate error!!!");
	        	System.out.println("请先登录！");
				return false;
		}*/
		//拦截不处理
	/*	if (servletPath.startsWith("/teacher/interactmsg/static/") || servletPath.startsWith("/parent/interactmsg/static/") || servletPath.startsWith("/teacher/my/static/")
					|| servletPath.startsWith("/teacherScore/static/") || servletPath.startsWith("/goldBean/static/") || servletPath.startsWith("/parentScore/static/")|| servletPath.startsWith("/teacherCard/static/")
					|| servletPath.startsWith("/parent/consume/static/")){
			return false;
		}*/
		//return true;
	}
	//清空session
    private void clearSession(HttpServletRequest request) {
 	   request.getSession().removeAttribute(Constant.SESSION_USER);
	   request.getSession().removeAttribute(Constant.SESSION_USER_ID);
	   request.getSession().removeAttribute(Constant.SESSION_NIKE_NAME);
	}

	/**
     * 在业务处理器处理请求执行完成后,生成视图之前执行的动作 ,可在modelAndView中加入数据
     */
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView mv) throws Exception {
	    
	}
	private boolean ERROR(HttpServletResponse response, String message) throws Exception {
        response.setHeader("content-type", "application/json;charset=UTF-8");

        JSONObject object = new JSONObject();
        object.put("status", 0);
        object.put("message", message);

        PrintWriter writer = response.getWriter();
        writer.print(object.toString());
        writer.flush();

        return false;
    }
	 private boolean NO_LOGIN(HttpServletResponse response) throws Exception {
	        response.setHeader("content-type", "application/json;charset=UTF-8");

	        JSONObject object = new JSONObject();
	        object.put("status", 2);
	        object.put("message", "Seesion已过期");

	        PrintWriter writer = response.getWriter();
	        writer.print(object);
	        writer.flush();

	        return false;
	    }

	    private boolean SUCCESS(HttpServletResponse response, String message) throws Exception {
	        response.setHeader("content-type", "application/json;charset=UTF-8");

	        JSONObject object = new JSONObject();
	        object.put("status", 1);
	        object.put("message", message);

	        PrintWriter writer = response.getWriter();
	        writer.print(object.toString());
	        writer.flush();

	        return false;
	    }

    /** 
     * 在DispatcherServlet完全处理完请求后被调用,可用于清理资源等  
     *  
     * 当有拦截器抛出异常时,会从当前拦截器往回执行所有的拦截器的afterCompletion() 
     */  
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		
	}
	

 
}
